<?php
/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @category   SabaiXOOPS
 * @package    SabaiXOOPS
 * @copyright  Copyright (c) 2008 myWeb Japan (http://www.myweb.ne.jp/)
 * @author     Kazumi Ono <onokazu@gmail.com>
 * @license    http://opensource.org/licenses/gpl-license.php GNU GPL
 * @link       http://sourceforge.net/projects/sabai
 * @version    0.1.9a2
 * @since      Class available since Release 0.1.0
 */
class SabaiXOOPS
{
    /**
     * Runs the XC module version of a Sabai application
     *
     * @static
     * @param Sabai_Application $app
     * @param Sabai_Controller $controller
     * @param string $moduleLib
     * @param string $moduleDirname
     */
    function run(&$app, &$controller, $moduleLib, $moduleDirname)
    {
        require_once 'Sabai/Request/Web.php';
        require_once 'Sabai/Response/Web.php';
        $request =& new Sabai_Request_Web();
        $response =& new Sabai_Response_Web(
                       SabaiXOOPS::getTemplate($app, $moduleLib, $moduleDirname),
                       XOOPS_URL . '/modules/' . $moduleDirname . '/layouts/default',
                       XOOPS_ROOT_PATH . '/modules/' . $moduleDirname . '/layouts/default'
                     );
        if (file_exists($css_file = XOOPS_ROOT_PATH . '/themes/' . $GLOBALS['xoopsConfig']['theme_set'] . '/' . $moduleLib . '/css/screen.css')) {
            $response->addCSSFile($css_file);
        }
        $user =& SabaiXOOPS::getCurrentUser($app->getRoles());
        Sabai_Application::run($controller, $request, $response, $user);
    }

    /**
     * Initializes a Sabai application as a XC module
     *
     * @static
     * @staticvar array $modules
     * @param Sabai_Application_Model $app
     * @param string $moduleDir
     * @return Sabai_Application_Model
     */
    function &toModule(&$app, $moduleDir)
    {
        static $modules = array();
        if (!isset($modules[$moduleDir])) {
            // clone app so that each module runs the app under its own config
            $app_clone = clone($app);
            $app_clone->setDBScheme(XOOPS_DB_TYPE);
            $app_clone->setDBPrefix(XOOPS_DB_PREFIX . '_' . strtolower($moduleDir) . '_');
            if (strpos(XOOPS_VERSION, '2.0.', 1)) {
                // disable auto encoding translation if 2.0.x
                $app_clone->setDBClientEncoding(_CHARSET);
            }
            $app_clone->setDBOptions(array('host'      => XOOPS_DB_HOST,
                                           'dbname'    => XOOPS_DB_NAME,
                                           'user'      => XOOPS_DB_USER,
                                           'pass'      => XOOPS_DB_PASS));
            // check if the current page is within this module
            if (isset($GLOBALS['xoopsModule'])
                  && isset($GLOBALS['xoopsModuleConfig'])
                  && $GLOBALS['xoopsModule']->getVar('dirname') == $moduleDir) {
                $configs = $GLOBALS['xoopsModuleConfig'];
            } else {
                // if not, load the module configuration variables
                $module_h =& xoops_gethandler('module');
                if (!$module =& $module_h->getByDirname($moduleDir)) {
                    trigger_error(sprintf('Requested module %s does not exist', $moduleDir), E_USER_ERROR);
                }
                $config_h =& xoops_gethandler('config');
                $configs =& $config_h->getConfigsByCat(0, $module->getVar('mid'));
            }
            foreach ($configs as $key => $value) {
                $app_clone->setConfig($key, $value);
            }
            $app_clone->setUserScheme('custom');
            $app_clone->setUserOptions(array('file'  => 'SabaiXOOPS/User/Authenticator.php',
                                             'class' => 'SabaiXOOPS_User_Authenticator'),
                                       array('file'  => 'SabaiXOOPS/User/IdentityFetcher.php',
                                             'class' => 'SabaiXOOPS_User_IdentityFetcher'));
            $modules[$moduleDir] =& $app_clone;
        }
        return $modules[$moduleDir];
    }

    /**
     * Gets a template object for a XC module
     *
     * @static
     * @staticvar array $templates
     * @param Sabai_Application $app
     * @param string $moduleLib
     * @param string $moduleDirname
     * @return Sabai_Template_Default
     */
    function &getTemplate(&$app, $moduleLib, $moduleDirname)
    {
        static $templates = array();
        if (!isset($templates[$moduleDirname])) {
            require_once 'Sabai/Template/Default.php';
            $module_tpldir = XOOPS_TRUST_PATH . '/modules/' . $moduleLib . '/templates';
            $templates[$moduleDirname] =& new Sabai_Template_Default(
                                             array($module_tpldir, $app->getPath() . '/templates'),
                                             array($module_tpldir . '/helpers' , $app->getPath() . '/templates/helpers'),
                                             array(
                                               'module_dir' => $moduleDirname
                                             ));
            $templates[$moduleDirname]->setLocator($app);
            // module installation specific template files
            if (is_dir($custom_tpldir = XOOPS_ROOT_PATH . '/modules/' . $moduleDirname . '/layouts/default/templates')) {
                $templates[$moduleDirname]->addTemplateDir($custom_tpldir);
            }
        }
        return $templates[$moduleDirname];
    }

    /**
     * Gets locale names from charset and lang settings in XC
     *
     * @static
     * @staticvar array $locales
     * @staticvar array $lang2locales
     * @return array
     */
    function getLocales()
    {
        static $locales;
        static $lang2locales = array(
                            'pt'    => array('ISO-8859-1' => 'Portuguese_Brasil.ISO8859-1',
                                             'UTF-8'      => 'pt_BR.UTF-8'),
                            'pt-br'    => array('ISO-8859-1' => 'Portuguese_Brasil.ISO8859-1',
                                             'UTF-8'      => 'pt_BR.UTF-8'),
                            'de'    => array('ISO-8859-1' => 'de_DE.ISO8859-1',
                                             'UTF-8'      => 'de_DE.UTF-8'),
                            'es'    => array('ISO-8859-1' => 'es_ES.ISO8859-1',
                                             'UTF-8'      => 'es_ES.UTF-8'),
                            'en'    => array('ISO-8859-1' => 'en_US.ISO8859-1',
                                             'UTF-8'      => 'en_US.UTF-8'),
                            'fr'    => array('ISO-8859-1' => 'fr_FR.ISO8859-1',
                                             'UTF-8'      => 'fr_Fr.UTF-8'),
                            'ko'    => array('EUC-KR'     => 'ko_KR.eucKR',
                                             'UTF-8'      => 'ko_KR.UTF-8'),
                            'ja'    => array('EUC-JP'     => array(
                                                              'ja_JP.eucJP',
                                                              'Japanese_Japan.20932'
                                                             ),
                                             'SHIFT_JIS'  => array(
                                                              'ja_JP.SJIS',
                                                              'Japanese_Japan.932'
                                                             ),
                                             'UTF-8'      => array(
                                                              'ja_JP.UTF-8',
                                                              'Japanese_Japan.65001'
                                                             )),
                            'zh-cn' => array('GB2312'     => 'zh_CN.GB2312',
                                             'EUC-CN'     => 'zh_CN.GB2312',
                                             'UTF-8'      => 'zh_CN.UTF-8'),
                            'zh-tw' => array('BIG5'       => 'zh_TW.BIG5',
                                             'UTF-8'      => 'zh_TW.UTF-8'),
                            'tw'    => array('BIG5'       => 'zh_TW.BIG5',
                                             'UTF-8'      => 'zh_TW.UTF-8'));
        if (!isset($locales)) {
            $lang = strtolower(_LANGCODE);
            $charset = strtoupper(_CHARSET);
            $locales = isset($lang2locales[$lang][$charset]) ? (array)$lang2locales[$lang][$charset] : array('en_US.ISO8859-1');
        }
        return $locales;
    }

    /**
     * Gets the current user object
     *
     * @static
     * @param array $roles
     * @return Sabai_User
     */
    function &getCurrentUser($roles)
    {
        require_once 'Sabai/User.php';
        if (isset($GLOBALS['xoopsUser']) && is_object($GLOBALS['xoopsUser'])) {
            $user =& new Sabai_User(SabaiXOOPS::getUserIdentity($GLOBALS['xoopsUser']), true);
            $groupperm_h =& xoops_gethandler('groupperm');
            if ($groupperm_h->checkRight('module_admin',
                                         $GLOBALS['xoopsModule']->getVar('mid'),
                                         $GLOBALS['xoopsUser']->getGroups())) {
                // Module admin gets all roles
                $user->setRoles(array_keys($roles));
            } else {
                $perm_name = $GLOBALS['xoopsModule']->getVar('dirname') . '_role';
                if ($perms = $groupperm_h->getItemIds($perm_name,
                                                      $GLOBALS['xoopsUser']->getGroups(),
                                                      $GLOBALS['xoopsModule']->getVar('mid'))) {
                    foreach ($perms as $role) {
                        $user->addRole($role);
                    }
                }
            }
        } else {
            $user =& new Sabai_User(SabaiXOOPS::getGuestIdentity(), false);
        }
        return $user;
    }

    /**
     * Gets an user object by login information
     *
     * @static
     * @param string $username
     * @param string $password
     * @param string $module
     * @param array $roles
     * @return Sabai_User
     */
    function &getUserByLogin($username, $password, $module = null, $roles = array())
    {
        $member_h =& xoops_gethandler('member');
        $xoops_user =& $member_h->loginUser(addslashes($username), $password);
        if (!is_object($xoops_user)) {
            $ret = false; return $ret;
        }
        require_once 'Sabai/User.php';
        $user =& new Sabai_User(SabaiXOOPS::getUserIdentity($xoops_user), true);
        if (isset($module) && is_object($module)) {
            $module_id = $module->getVar('mid');
            $groupperm_h =& xoops_gethandler('groupperm');
            if ($groupperm_h->checkRight('module_admin',
                                         $module_id,
                                         $xoops_user->getGroups())) {
                // Module admin gets all roles
                $user->setRoles(array_keys($roles));
            } else {
                $perm_name = $module->getVar('dirname') . '_role';
                if ($perms = $groupperm_h->getItemIds($perm_name, $xoops_user->getGroups(), $module_id)) {
                    foreach ($perms as $role) {
                        $user->addRole($role);
                    }
                }
            }
        }
        return $user;
    }

    /**
     * Gets a registered user identity
     *
     * @param XoopsUser $xoopsUser
     * @return Sabai_User_IDentity
     * @static
     */
    function &getUserIdentity(&$xoopsUser)
    {
        $uid = $xoopsUser->getVar('uid');
        $identity =& new Sabai_User_Identity($uid);
        $identity->setName($xoopsUser->getVar('uname'));
        $identity->setEmail($xoopsUser->getVar('email'));
        $identity->setProfileURL(XOOPS_URL . '/userinfo.php?uid=' . $uid);
        $identity->setURL($xoopsUser->getVar('url'));
        $identity->setImage(XOOPS_URL . '/uploads/' . $xoopsUser->getVar('user_avatar'));
        return $identity;
    }

    /**
     * Gets a guest user identity
     *
     * @return Sabai_User_Identity
     * @static
     */
    function &getGuestIdentity()
    {
        $identity =& new Sabai_User_Identity(0);
        $identity->setName($GLOBALS['xoopsConfig']['anonymous']);
        $identity->setImage(XOOPS_URL . '/uploads/blank.gif');
        return $identity;
    }
}